package com.nullpointer.xchat.fragment;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.nullpointer.xchat.MainActivity;
import com.nullpointer.xchat.R;
import com.nullpointer.xchat.adapter.ResultFindFriendAdapter;
import com.nullpointer.xchat.object.User;

public class FindFriendResultsFragment extends DialogFragment {

	private ViewPager vpResult;
	private ResultFindFriendAdapter adapter;
	private final static String USERS_KEY = "USERS_KEY";
	private List<User> users = new ArrayList<>();
	private Button btSendMessage;
	private Button btSkip;

	public static FindFriendResultsFragment newInstance(List<User> users) {
		FindFriendResultsFragment f = new FindFriendResultsFragment();
		Bundle args = new Bundle();
		args.putString(USERS_KEY, User.toJsonArray(users));
		f.setArguments(args);
		return f;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		String value = getArguments().getString(USERS_KEY);
		if (value == null) {
			dismiss();
			return;
		}
		users.clear();
		users.addAll(User.fromJsonArrayToUsers(value));
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_find_resutls, container);
		findViewIds(view);
		init();
		setEvent();
		return view;
	}

	private void init() {
		getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
		adapter = new ResultFindFriendAdapter(getChildFragmentManager(), users);
		vpResult.setAdapter(adapter);
		vpResult.setOffscreenPageLimit(3);
	}

	private void setEvent() {
		btSendMessage.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				User user = users.get(vpResult.getCurrentItem());
				if (user.getUserID() == null) {
					dismiss();
					return;
				}
				((MainActivity) getActivity()).showChatPrivate(user.getUserID(), user.getName(),
						false);
				dismiss();

			}
		});
		btSkip.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				int currentPos = vpResult.getCurrentItem();
				currentPos++;
				if (currentPos >= users.size()) {
					dismiss();
				}
				vpResult.setCurrentItem(currentPos, true);
			}
		});
	}

	private void findViewIds(View view) {
		vpResult = (ViewPager) view.findViewById(R.id.vp_result);
		btSendMessage = (Button) view.findViewById(R.id.bt_send_message);
		btSkip = (Button) view.findViewById(R.id.bt_skip);
	}
}
